<?php
/**
 * [ Random Framework ]
 *
 * @version 2.0.0 (build 20130520)
 *
 * @link http://0x00.sinaapp.com/random.html
 * 
 * @author Coseylee (Coseylee@gmail.com).
 *
 */

class rewrite_route extends random_route
{
	function url_parse()
	{
		$_GET = array(); // 清空 $_GET
		$query_string = isset($_SERVER['QUERY_STRING']) ? trim($_SERVER['QUERY_STRING']) : '';
		$query_string = explode('?', $query_string);
		$query_string['path'] = isset($query_string[0]) ? $query_string[0] : '';
		$query_string['query'] = isset($query_string[1]) ? $query_string[1] : '';
		/**
		 * 20110917
		 * 以下IF语句修复入口文件直接加?aaa=bbb形式参数时，无法正确判取得默认控制器及动作
		 */
		if (!isset($query_string['query']) && $_SERVER['QUERY_STRING'] === $query_string['path'])
		{
			$query_string['path'] = $this -> config['controller'].$this -> config['rewrite_separator'].$this -> config['action'];
			$query_string['query'] = $_SERVER['QUERY_STRING'];
		}
		$query = explode($this -> config['rewrite_separator'], $query_string['path']);
		if (isset($query_string['query']))
		{
			parse_str($query_string['query'], $_GET);
			// 不允许使用GET传递ACTION和CONTROLLER
			unset($_GET[$this -> config['controller_name']], $_GET[$this -> config['action_name']]);
		}
		$query = array_filter($query);
		
		if (count($query) > 0)
		{
			// 处理后缀
			if ($this -> config['rewrite_suffix'] != '')
			{
				$last_query = & $query[count($query)-1];
				if (strrpos($last_query, $this -> config['rewrite_suffix']) === ($length = strlen($last_query) - strlen($this -> config['rewrite_suffix'])))
				{
					$last_query = substr($last_query, 0, -strlen($this -> config['rewrite_suffix']));
				}
				else if (empty($_GET))
				{
					$forward = $GLOBALS['RANDOM']['route']['url_base'];
					$forward = (dirname($forward) != '\\' ? dirname($forward) : '').'/'.$query_string['path'].$this -> config['rewrite_suffix'];
					header('Location: '.$forward);
				}
				unset($last_query);
			}
			
			foreach ($query as $k => $v)
			{
				if(intval($k) == 0)
				{
					if (isset($this -> config['rewrite_map'][$v]))
					{
						$args_name = $v;
						list($_GET[$this -> config['controller_name']], $_GET[$this -> config['action_name']]) = explode('#', $this -> config['rewrite_map'][$v], 2);
					}
					else
					{
						$_GET[$this -> config['controller_name']] = $v;
					}
				}
				else
				{
					// 是否已映射并且有rewrite_args需要解析
					if (isset($args_name) && isset($this -> config['rewrite_args'][$args_name]))
					{
						if (isset($this -> config['rewrite_args'][$args_name][$k-1]))
						{
							$_GET[$this -> config['rewrite_args'][$args_name][$k-1]] = $v;
						}
						else
						{
							// 当URL中参数多于 rewrite_args 中个数，再次拆分
							$yu = (count($this -> config['rewrite_args'][$args_name])+1)%2;
							if ($k%2 == $yu)
							{
								//echo $v.'<br />';
								$_GET[strval($v)] = isset($query[$k+1]) ? $query[$k+1] : '';
							}
						}
					}
					// 不需要解析rewrite_args
					else
					{
						// 如果没有映射，设置 ACTION 名
						if (!isset($args_name) && $k == 1)
						{
							$_GET[$this -> config['action_name']] = $v;
						}
						// 否则拆分
						else
						{
							// rewrite_args 解析与不解析相差一位
							$yu = isset($args_name) ? 1 : 0;
							if ($k%2 == $yu)
							{
								$_GET[$v] = isset($query[$k+1]) ? $query[$k+1] : '';
							}
						}
					}
				}
			}
		}
	}
	
	function url_create($controller = '', $action = '', $args = array(), $query_string = '')
	{
		$config = $GLOBALS['RANDOM']['route'];
		$url = $config['url_base'];
		$url = str_replace('\\', '/', dirname($url)) === '/' ? '/' : dirname($url).'/';
		
		if ($controller === '' && $action === '' && empty($args))
		{
			return $url;
		}
		
		if (in_array($controller.'#'.$action, $config['rewrite_map']))
		{
			$rewrite_map = array_flip($config['rewrite_map']);
			$rewrite_map = $rewrite_map[$controller.'#'.$action];
			$url .= $rewrite_map;
		}
		else
		{
			if ($controller === '')
			{
				$controller = $config['controller'];
			}
			$url .= $controller;
			if ($action !== '' || !empty($args))
			{
				$action = $action === '' ? $config['action'] : $action;
				$url .= $config['rewrite_separator'].$action;
			}
		}
		
		if (isset($rewrite_map) && isset($config['rewrite_args'][$rewrite_map]))
		{
			$other = array();
			foreach ($config['rewrite_args'][$rewrite_map] as $name)
			{
				if (isset($args[$name]))
				{
					$url .= $config['rewrite_separator'].$args[$name];
					unset($args[$name]);
				}
			}
		}
		
		foreach ($args as $key => $value)
		{
			$url .= $config['rewrite_separator'].$key.$config['rewrite_separator'].$value;
		}
		$url .= $config['rewrite_suffix'];
		
		if ($query_string !== '')
		{
			$url .= '?'.$query_string;
		}
		return $url;
	}
}
